#!/usr/bin/python

import urllib2,urllib
#import webbrowser
import cookielib
#from http.client import HTTPConnection
import getpass
import os
import sys


def usage():
    print "Usage: ./syncemacs.py upload|download"
#process parameter from terminal
if len(sys.argv)<2:
    usage()
    exit()
# #for i in sys.argv[1:]:
# #    print i
mode = sys.argv[1]
if(mode!='upload' and mode!='download'):
    usage()
    exit()


try:
    import mechanize
except ImportError:
    os.system("rm -f mechanize.tar.gz")
    os.system("wget http://sk-chang.googlecode.com/files/mechanize.tar.gz")
    os.system("tar xfz mechanize.tar.gz")
    import mechanize
    #f = urllib2.urlopen("http://sk-chang.googlecode.com/files/mechanize.tar.gz").read()

try:
    from BeautifulSoup import BeautifulSoup
except ImportError:
    os.system("rm -f BeautifulSoup.py")
    os.system("wget http://sk-chang.googlecode.com/files/BeautifulSoup.py")
    from BeautifulSoup import BeautifulSoup


status  = ""

def login_google(Email, Passwd):
    global br, status
    r = br.open("https://www.google.com/accounts")
    html = r.read()
    # Select the first (index zero) form
    br.select_form(nr=0)
    br.form['Email']=Email
    br.form['Passwd']=Passwd
    br.submit()
    resp_html =  br.response().read()	#br.response().read() is needed
    #for debug
    #save(resp_html)
    #must parse resp_html to make sure really logged in !
    logsoup = BeautifulSoup(resp_html)
    logout = logsoup.find("a",{"href" : "https://www.google.com/accounts/Logout"})
    if logout == None:
        #print "login error, please check your password or network connection ..."
        status = "login error, please check your password or network connection ..."
        return 0
    else:
        #print "login succeed !"
        status = "login succeed !"
        return 1


def upload_to_google(filename, summary="upload file", description=''):
    global br
    upload_page = "http://code.google.com/p/sk-chang/downloads/entry"
    r = br.open(upload_page)
    br.select_form(nr=2)
    br.form['summary'] = summary		#"upload test 1"
    br.form['description'] = description	#"description 1"
    #filename = "/home/sk/hello.c"
    #br.form.add_file(open(filename), 'text/plain', filename)
    br.form.add_file(open(filename), 'application/octet-stream', filename)
    br.submit()
    resp_html =  br.response().read()




#modified for upload Emacs Profile
#return 
# -1 : rename emacs profile error!
#  0 : emacsprofile not exist, please try this program again !
#  1 : upload succeed !
def upload_emacsprofile_to_google():
    global br, status
    upload_page = "http://code.google.com/p/sk-chang/downloads/entry"
    r = br.open(upload_page)

#get current date from the page
    soup = BeautifulSoup(r)
    #debug
    #print soup.prettify()
    #save(soup.prettify())
    date_td = soup.find(lambda tag: tag.name=='td' and tag.input!=None and ((u'id', u'release_date') in tag.input.attrs) )
    #print date_td
    #date = date_td.text
    date = date_td.contents[0].strip()
    #print date
    emacsprofile = "emacsprofile-"+date+".tar.gz";	#need a random suffix ?
    #print emacsprofile


    #go to user's home directory
    home = os.path.expanduser('~')
    os.chdir(home)
    
    br.select_form(nr=2)
    br.form['summary'] = emacsprofile
    br.form['description'] = emacsprofile
    #filename = "/home/sk/hello.c"
    #br.form.add_file(open(filename), 'text/plain', filename)
    

    if os.path.isfile("emacsprofile.tar.gz"):
        res =  os.system("mv emacsprofile.tar.gz "+emacsprofile)
        if res:
            #print "rename emacsprofile.tar.gz to "+emacsprofile+" error!"
            status = "rename emacsprofile.tar.gz to "+emacsprofile+" error!"
            return -1   

    if not os.path.isfile(emacsprofile):
        status = emacsprofile+" not exist, please try this program again !" 
        return 0
        

    br.form.add_file(open(emacsprofile), 'application/octet-stream', emacsprofile)

    br.submit()
    resp_html =  br.response().read()
    save(resp_html)
    os.system("rm -f "+emacsprofile)
    #print  "upload succeed ! Current version is "+emacsprofile
    status = "upload succeed ! Current version is "+emacsprofile
    return 1




def save(data):
    f = open("tmp.html", "w")
    f.write(data)
    f.close()




#return :
#-1 : run tar command error
# 0 : no file need to be packaged
# 1 : Package Emacs Profile Succeed !

def packEmacsProfile():
    global status
    home = os.path.expanduser('~')
    os.chdir(home)
    #filelist = ''
    filelist = '.emacs '	#file in "~/" directory
    base = ".emacs.d"
    #process all files under the directory
    for root, dirs, files in os.walk(home+'/'+base):
    	#print files
        if(files==[]):
            #print "no files"
            pass
        else:
            for f in files:
            	#print f
                filelist += base+"/"+f+" "

    	#process all subdirs 
    	#print dirs
        dirs.remove('auto-save-list')	#remove unuseful directory
        if(dirs==[]):
            #print 'no subdirs need to be saved'
            pass
        else:
            for d in dirs:
            	#print d
                filelist += base+"/"+d+" "

    	#finished
        break
    #print filelist
    if(filelist==''):
        #print "no file need to be packaged"
        status = "no file need to be packaged"
        return 0
    else:
        #print "filelist : ",filelist
        cmd = "tar cfz emacsprofile.tar.gz "+filelist
    	#print cmd
        if(os.system(cmd)):
            #print "run tar error"
            status = "run tar command error"
            return -1
        else:
            #print "Package Emacs Profile Succeed !"
            status = "Package Emacs Profile Succeed !"
            return 1





def uploadCurrentEmacsProfile():
    try:
        res = packEmacsProfile()
    except:
        return -1
    
    if(res==1):
        #print "Succeed Pacakged!"
        print "commiting ......"
        try:
            upload_emacsprofile_to_google()
        except:
            return -2
        print "upload OK!"
        return 1
    elif(res==0):
        return 0
    else:
        print "Packaged Error !"
        return -3
    




#login_page = "https://www.google.com/accounts"
#download_page = "http://code.google.com/p/sk-chang/downloads/list"
#upload_page = "http://code.google.com/p/sk-chang/downloads/entry"
#url = "http://www.google.com"

# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
# If the protected site didn't receive the authentication data you would
# end up with a 410 error in your face
#br.add_password('http://safe-site.domain', 'username', 'password')
#br.open('http://safe-site.domain')
#br.add_password(url, "", "")
# Open some site, let's pick a random one, the first that pops in mind:
#r = br.open('http://google.com')


# #download file from code.google.com/p/sk-chang
# soup = BeautifulSoup(urllib2.urlopen("http://code.google.com/p/sk-chang/downloads/list"))
# downtable = soup.find("table",{"id" : "resultstable"})
# downlist = downtable.findAll("td", {"class" : "vt id col_0"})
# for item in downlist:
#     page = "http://code.google.com/p/sk-chang/downloads/"+item.a['href']
#     s = BeautifulSoup(urllib2.urlopen(page))
#     box = s.find("div", {"class" : "box-inner"})
#     print box.a['href']
# #save(downlist.prettify())
#exit()

#download & apply last emacs profile file from http://code.google.com/p/sk-chang
def applyLastEmacsProfile():
    global status
    soup = BeautifulSoup(urllib2.urlopen("http://code.google.com/p/sk-chang/downloads/list"))
    downtable = soup.find("table",{"id" : "resultstable"})
    downlist = downtable.find("td", {"class" : "vt id col_0"})
    page = "http://code.google.com/p/sk-chang/downloads/"+downlist.a['href']
    s = BeautifulSoup(urllib2.urlopen(page))
    link = s.find("div", {"class" : "box-inner"}).a['href']
    #modify 2011.8.10
    if link[0:2] == "//":
        link = "http:" + link
    #
    print "The last profile link is :"
    print link
    
    profile = urllib2.urlopen(link).read()
    os.chdir(os.path.expanduser('~'))
    f = open("emacsprofile.tar.gz", "w")
    f.write(profile)
    f.close()
    
    res = os.system("tar xfz emacsprofile.tar.gz")
    if(res):
        #print "run tar command error !"
        status = "run 'tar xfz emacsprofile.tar.gz' error !"
        return 0
    else:
        os.system("rm emacsprofile.tar.gz")
        status = "Apply Last Emacs Profile Succeed !"
        return 1
    

if(mode=='download'):
    #download & apply last emacs profile
    i = 10
    while i:
        try:
            res = applyLastEmacsProfile()
            print status
            #exit()	#exit() in try cannot exit yet
            break
        except:
            print "download fatal error ,try again ...", 11-i 
            i -= 1

    if(i==0):
        print "download fatal Error for 10 times, Please check the network connection ......"

    exit()


if(mode=='upload'):
    #get password & login
    #Passwd = raw_input("Google Password: ")
    Passwd = getpass.getpass('Google Password:')
    #print Passwd

#first login google
    i = 10
    while i:
        if(i==10):
            print "login google ..."
        else:
            print "login error, try again ...",10-i
            
        result = login_google("kernel0722@gmail.com", Passwd)
        if(result==0):
            i -= 1
        else:
            break
        
    if(i==0):
        print "Login Google Error for 10 times, Please check your password or the network connection ......"
        exit()
    else:
        print "login succeed !"

    #exit()


#then, package current emacs profile
    print "package current emacs profile ..."
    res = packEmacsProfile()
    print status
    if(res!=1):		#package failed
        exit()

    #exit()


#last, upload packaged profile
    print "upload packaged profile ..."
    i  = 10
    while i:
        try:
            res = upload_emacsprofile_to_google()
            print status
            #exit()	#upload succeed! or some error not need to try again #here exit() make a except and cannot exit
            break
        except:
            print "upload fatal error ,try again ...", 11-i 
            i -= 1
            

    if(i==0):
        print "upload fatal Error for 10 times, Please check the network connection ......"

    exit()


usage()
exit()


# #check if logged in or not 
# r = br.open("https://www.google.com/accounts")
# html = r.read()
# save(html)

#upload file
#for i in range(1,30):
#    upload_to_google("/home/sk/tmp/hello_"+str(i)+".c", "summary "+str(i))
#upload_to_google("/home/sk/tmp2.py");




    

#if __name__ == "__main__":
#    main()
